#pragma once
#include<sys/socket.h>
#include<sys/types.h>
#include<string>
#include<iostream>
#include<netinet/in.h>
#include<arpa/inet.h>>
class Udpserve
{
    public:
    Udpserve()
    {}
    ~Udpserve()
    {}
    void Init()
    {
        //创建套接字：
        int socketfd=socket(AF_INET,SOCK_DGRAM,0);
        if(socketfd<0)
        {
            std::cout<<"socket creat fail!"<<std::endl;
            exit(1);
        }
        std::cout<<"socket success!"<<std::endl;
        //创建socketaddr_in并绑定ip与端口
        struct sockaddr_in local;
        //这里_ip与_port需要转化为网络字节序也就是大端
        local.sin_family=AF_INET;
        local.sin_port=htons(_port);
        local.sin_addr.s_addr=inet_addr(_ip.c_str());
        //将填写好的sockaddr_in与套接字绑定
        int len=sizeof(local);
        int ret=bind(_sockfd,(const struct sockaddr*)&local,len);\
        if(ret<0)
        {
            std::cout<<"bind fail!"<<std::endl;
            exit(2);
        }
        std::cout<<"bind success!"<<std::endl;
    }
    void Start()
    {
        while(1)
        {
            char rec_buffer[1024];
            struct sockaddr_in peer;
            unsigned int len=sizeof(peer);
            int ret=recvfrom(_sockfd,rec_buffer,sizeof(rec_buffer)-1,0,(struct sockaddr*)&peer,&len);
            if(ret<0)
            {
                std::cout<<"recvfrom fail!"<<std::endl;
                exit(3);
            }
            rec_buffer[ret]='0';
            std::cout<<"client say:"<<rec_buffer<<std::endl;
            std::string echoserver="server say@:";
            echoserver+=rec_buffer;
            int ret=sendto(_sockfd,echoserver.c_str(),echoserver.size(),0,(const struct sockaddr*)&peer,len);
        }
    }
    private:
    int _sockfd;
    std::string _ip;
    __uint16_t _port;
};